class Api::V1::UserCouponsController < Api::V1::BaseController
  def index
    @user_coupons = UserCoupon.all
    if params[:state].presence
      @user_coupons = @user_coupons.where(state: params[:state])
      if params[:state] == :unused
        @user_coupons = @user_coupons.joins(:coupon).where("coupons.end_at >= ?", Time.now.to_datetime)
      end
    end
    @user_coupons = @user_coupons.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def create
    if params[:coupon_id].blank?
      render json: { result: false, message: '缺少参数.' }, status: :ok and return
    end
    coupon = Coupon.find_by_id params[:coupon_id]
    if coupon.blank?
      render json: { result: false, message: '找不到该优惠券.' }, status: :ok and return
    end
    if coupon.overdue? || coupon.end_at < Time.now.to_datetime
      render json: { result: false, message: '该优惠券已过期.' }, status: :ok and return
    end
    user_coupon = UserCoupon.where(user_id: @current_user.id, coupon_id: params[:coupon_id]).first
    if user_coupon.presence
      render json: { result: false, message: '你已领取该优惠券.' }, status: :ok and return
    end
    user_coupon = UserCoupon.new
    user_coupon.user_id = @current_user.id
    user_coupon.coupon_id = params[:coupon_id]
    user_coupon.state = :unused
    if user_coupon.save
      render json: { result: true, message: '领取成功.' }, status: :ok and return
    else
      render json: { result: false, message: '领取失败.', data: { errors: render_errors(user_coupon.errors.messages) } }, status: :ok and return
    end
  end
  
end
